import requests
import json
import sys
import random
from pathlib import Path
sys.path.append(str(Path(__file__).parent.parent))
from reqapi.api import BaseApi
from com.db.scan_account_manager import ScanAccountManager

class GetCommodityListApi(BaseApi):
    def __init__(self, device_token, device_id, auth_token, uk, user_id):
        super().__init__(device_token, device_id, auth_token, uk)
        self.user_id = user_id

    def execute(self, max_abrade=None, max_price=None, min_abrade=None, template_id=None,page_size=10):
        """
        执行API请求
        
        Args:
            max_abrade: 最大磨损度，默认0.18
            max_price: 最高价格，默认70
            min_abrade: 最小磨损度，默认0.15
            template_id: 模板ID，默认108581
        """
        # 设置默认参数
        params = {
            'auto_delivery': 0,
            'has_sold': "true",
            'have_bu_zhang_type': 0,
            'list_sort_type': "1",
            'list_type': 10,
            'max_abrade': max_abrade or "0.18",
            'max_price': max_price,
            'merge_flag': 0,
            'min_abrade': min_abrade or "0.15",
            'min_price': "0" if max_price is not None else None,
            'page_index': 1,
            'page_size': page_size,
            'presale_more_zones': 2,
            'sort_type': "1",
            'sort_type_key': "SELL_PRICE_ASC",
            'source_channel': "",
            'status': "20",
            'sticker_abrade': 0,
            'stickers_is_sort': False,
            'template_id': template_id or "108581",
            'ultra_long_lease_more_zones': 0,
            'user_id': self.user_id,
            'session_id': self.device_id
        }

        url = f"{self.BASE_URL}/api/homepage/v2/detail/commodity/list/sell"
        
        data = {
            "autoDelivery": params["auto_delivery"],
            "hasSold": params["has_sold"],
            "haveBuZhangType": params["have_bu_zhang_type"],
            "listSortType": params["list_sort_type"],
            "listType": params["list_type"],
            "maxAbrade": params["max_abrade"],
            "mergeFlag": params["merge_flag"],
            "minAbrade": params["min_abrade"],
            "pageIndex": params["page_index"],
            "pageSize": params["page_size"],
            "presaleMoreZones": params["presale_more_zones"],
            "sortType": params["sort_type"],
            "sortTypeKey": params["sort_type_key"],
            "sourceChannel": params["source_channel"],
            "status": params["status"],
            "stickerAbrade": params["sticker_abrade"],
            "stickersIsSort": params["stickers_is_sort"],
            "templateId": params["template_id"],
            "ultraLongLeaseMoreZones": params["ultra_long_lease_more_zones"],
            "userId": params["user_id"],
            "Sessionid": params["session_id"]
        }
        
        if 'max_price' in params and params['max_price'] is not None:
            data["maxPrice"] = params["max_price"]
        if 'min_price' in params and params['min_price'] is not None:
            data["minPrice"] = params["min_price"]

        headers = self.common_headers
        
        print("请求头:")
        print(json.dumps(headers, indent=2, ensure_ascii=False))
        print("\n请求参数:")
        print(json.dumps(data, indent=2, ensure_ascii=False))
        
        response = self.interceptor.send_request(url, json=data, headers=headers, need_encrypt=False)
        try:
            return response
        except Exception as e:
            print(f"请求失败: {e}")
            return response

def main():
    # 从数据库随机获取一个状态为可用的账号
    # account_manager = ScanAccountManager()
    # active_accounts = account_manager.get_active_accounts()
    
    # if not active_accounts:
    #     print("没有找到可用的账号")
    #     return
    
    # # 随机选择一个账号
    # random_account = random.choice(active_accounts)
    
    # print(f"随机选择的账号: ID={random_account['id']}, 名称={random_account.get('name', 'N/A')}")
    
    # # 获取账号信息
    # device_id = random_account.get('device_id', '')
    # auth_token = random_account.get('uu_token', '')
    # uk = random_account.get('uk', '')
    # user_id = random_account.get('uu_user_id', '')

    device_id = "Z/h2N6xfPj4DAF762L/8Q7lC"
    auth_token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJqdGkiOiJmOTI0ZTZjMjdkMDQ0MTliOWM0OGQ2NzA1MzZhZjdhMyIsIm5hbWVpZCI6IjEwODAxMjY0IiwiSWQiOiIxMDgwMTI2NCIsInVuaXF1ZV9uYW1lIjoiNDAzMiIsIk5hbWUiOiI0MDMyIiwidmVyc2lvbiI6Ilk2QyIsIm5iZiI6MTc0NDM0MzI0NSwiZXhwIjoxNzQ3NTUwODQ1LCJpc3MiOiJ5b3VwaW44OTguY29tIiwiZGV2aWNlSWQiOiJaL2gyTjZ4ZlBqNERBRjc2MkwvOFE3bEMiLCJhdWQiOiJ1c2VyIn0.pxQrWFPYxZ-c0FipINk4F9j9JGZ6fqGHU0aitVe_LFk"
    uk = "5FHvREuFMkm3Cm9szK0GXHuqD6TzkewexziGv6bByyX8FH2RftdCyox9uZL0GR31M"
    user_id = "10801264"
    
    if not device_id or not auth_token or not uk or not user_id:
        print("账号信息不完整，缺少必要的认证信息")
        return
    
    # 确保auth_token格式正确
    if not auth_token.startswith("Bearer "):
        auth_token = f"Bearer {auth_token}"

    api = GetCommodityListApi(device_id, device_id, auth_token, uk, user_id)
    result = api.execute(
        max_abrade="0.18",
        max_price="70",
        min_abrade="0.15",
        template_id="108581"
    )
    print(result)

if __name__ == "__main__":
    main()
